#!/usr/bin/env python3
"""
简化的 MCP 工具配置验证
"""

import asyncio
import sys
import os
import json

# 添加项目根目录到 Python 路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

try:
    from src.config import load_config
    from src.database.manager import DatabaseManager
    print("✅ 成功导入配置和数据库管理器")
except ImportError as e:
    print(f"❌ 导入失败: {e}")
    sys.exit(1)

async def test_mcp_tools():
    """测试 MCP 工具配置"""
    print("=== MCP 工具配置验证 ===")
    
    try:
        # 1. 加载配置
        print("\n1. 加载配置...")
        config = load_config()
        print("✅ 配置加载成功")
        
        # 2. 初始化数据库管理器
        print("\n2. 初始化数据库连接...")
        db_manager = DatabaseManager(config)
        await db_manager.initialize()
        print("✅ 数据库连接初始化成功")
        
        # 3. 测试 conversation_search
        print("\n3. 测试 conversation_search...")
        chromadb_client = db_manager.chromadb_client
        
        search_results = await chromadb_client.search_conversations(
            query="王者荣耀",
            user_id="default_user",
            limit=5
        )
        
        print(f"   搜索结果数量: {len(search_results) if search_results else 0}")
        
        if search_results and len(search_results) > 0:
            print("   ✅ conversation_search 工作正常")
            print(f"   前3个结果:")
            for i, result in enumerate(search_results[:3]):
                content = result.get('content', '')[:50] + '...' if len(result.get('content', '')) > 50 else result.get('content', '')
                print(f"     {i+1}. {content}")
        else:
            print("   ❌ conversation_search 返回空结果")
        
        # 4. 测试 find_related_concepts
        print("\n4. 测试 find_related_concepts...")
        neo4j_client = db_manager.neo4j_client
        
        if hasattr(neo4j_client, 'find_related_concepts'):
            concept_results = await neo4j_client.find_related_concepts("王者荣耀", limit=5)
            print(f"   概念搜索结果数量: {len(concept_results) if concept_results else 0}")
            
            if concept_results:
                print("   ✅ find_related_concepts 工作正常")
                print(f"   前3个相关概念:")
                for i, concept in enumerate(concept_results[:3]):
                    name = concept.get('name', 'unknown')
                    strength = concept.get('connection_strength', 0)
                    print(f"     {i+1}. {name} (强度: {strength})")
            else:
                print("   ❌ find_related_concepts 返回空结果")
        else:
            print("   ❌ Neo4jClient 缺少 find_related_concepts 方法")
        
        # 5. 模拟 MCP 调用
        print("\n5. 模拟 MCP 调用...")
        
        # 模拟 conversation_search MCP 调用
        mcp_params = {"query": "王者荣耀", "user_id": "default_user", "limit": 5}
        print(f"   MCP 输入参数: {json.dumps(mcp_params, ensure_ascii=False)}")
        
        mcp_results = await chromadb_client.search_conversations(
            query=mcp_params["query"],
            user_id=mcp_params["user_id"],
            limit=mcp_params["limit"]
        )
        
        mcp_response = {
            'success': True,
            'results': mcp_results,
            'count': len(mcp_results) if mcp_results else 0
        }
        
        print(f"   MCP 输出结果: success={mcp_response['success']}, count={mcp_response['count']}")
        
        if mcp_response['count'] > 0:
            print("   ✅ MCP conversation_search 工具配置正确")
        else:
            print("   ❌ MCP conversation_search 工具返回空结果")
        
        # 6. 最终结论
        print("\n6. 验证结论...")
        if (search_results and len(search_results) > 0) and mcp_response['count'] > 0:
            print("   🎉 MCP 工具配置验证通过！")
            print("   数据仓库配置与实际存储数据的仓库一致。")
        else:
            print("   ⚠️  MCP 工具配置存在问题，需要进一步检查。")
        
        # 关闭数据库连接
        await db_manager.close()
        print("\n✅ 数据库连接已关闭")
        
    except Exception as e:
        print(f"❌ 测试过程中发生错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(test_mcp_tools())